package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.*;
import com.entrogy.dao.ClassMapper;
import com.entrogy.dao.SchoolMapper;
import com.entrogy.dao.StudentMapper;
import com.entrogy.dao.UtilsMapper;
import com.entrogy.service.UtilsService;
import com.entrogy.timing.ChangePersonTimeThread;
import com.entrogy.timing.TimingTaskService;
import com.entrogy.utils.Base64Utils;
import com.entrogy.utils.THDio;
import com.entrogy.utils.constants.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @ClassName UtilsServiceImpl
 * @Description
 * @Author luoxingjiang
 * @Date 2019-11-13 下午 5:30
 * @Version 1.0
 **/
@Service
public class UtilsServiceImpl implements UtilsService {

    private static final Logger logger = LoggerFactory.getLogger(UtilsServiceImpl.class);

    @Autowired
    private THDio thDio;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private UtilsMapper utilsMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassMapper classMapper;


    @Override
    public List<StudentEntity> resetMultipleNameStudentPhoto(Integer schoolCode) {

        List<JSONObject> schoolList = schoolMapper.listSchool(null);
        List<StudentEntity> failStudentList = new ArrayList<>();
        for (JSONObject jsonObject : schoolList) {
            schoolCode = jsonObject.getInteger("schoolCode");
            if (schoolCode.equals(1) || schoolCode.equals(510182000) || schoolCode.equals(510182006)){
                continue;
            }
//            if (!schoolCode.equals(510107000)){
//                continue;
//            }
            String deviceIds = new TimingTaskService().getDeviceIds(false, schoolCode, Constants.THDID_AI06);//获取该学校的所有闸机设备
            // 照片有问题的学生
            // 查找同名学生
            List<JSONObject> multipleNameStudentList = utilsMapper.listMultipleNameStudent(schoolCode);
            String schoolName = schoolMapper.getSchoolName(schoolCode);
            logger.info("正在进行同名学生照片校正=>" + multipleNameStudentList);
            SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
            for (JSONObject multipleNameStudent : multipleNameStudentList) {
                String studentName = multipleNameStudent.getString("studentName");
                String[] studentIdList = multipleNameStudent.getString("studentIdList").split(",");
                for (String studentId : studentIdList) {
                    StudentEntity studentEntity = studentMapper.getStudentById(Integer.valueOf(studentId));
                    // 删除这些在实义德后台的同名学生
                    int thdidId = studentEntity.getStudentThdid();
                    net.sf.json.JSONObject params = new net.sf.json.JSONObject();
                    params.put("personnel_id", thdidId);
                    params.put("type", 1);
                    logger.info("正在删除学生=>" + studentEntity.getStudentName() + studentEntity.getId());
                    net.sf.json.JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), "/personnel/delete", params, false, schoolThdidUrl.getAccessToken());
                    logger.info("删除结果=>" + res);

                    // 查找该学生的班级信息
                    ClassEntity classById = classMapper.getClassById(studentEntity.getCourseId(), schoolCode);
                    String className = classById.getClassName();

                    // 添加学生
                    net.sf.json.JSONObject addStudentParams = new net.sf.json.JSONObject();
                    addStudentParams.put("ic_number", studentEntity.getIdentity());
                    addStudentParams.put("id_number", studentEntity.getIdentity());
                    addStudentParams.put("name", studentEntity.getStudentName());
                    addStudentParams.put("group_id", schoolThdidUrl.getStudentGroupId()); // TODO 分组ID问题 这个是必须字段 ---------------------------
                    addStudentParams.put("phonenumber", "");
                    addStudentParams.put("gender", studentEntity.getSex());

                    // 图片格式
                    String photoFormat;

                    String studentPhotoUrl = "D:\\学校信息"
                            + File.separator + schoolName
                            + File.separator + "student"
                            + File.separator + className.substring(0, 6)
                            + File.separator + String.valueOf(classById.getId()).substring(4, 5)
                            + File.separator + studentName + ".png";
                    try {
                        photoFormat = ".png";
                        addStudentParams.put("base_image", Base64Utils.ImageToBase64ByLocal(studentPhotoUrl));
                    }catch (Exception e){
                        try{
                            studentPhotoUrl = "D:\\学校信息" + File.separator + schoolName
                                    + File.separator + "student"
                                    + File.separator + className.substring(0, 6)
                                    + File.separator + String.valueOf(classById.getId()).substring(4, 5)
                                    + File.separator + studentName + ".jpg";
                            photoFormat = ".jpg";
                            addStudentParams.put("base_image", Base64Utils.ImageToBase64ByLocal(studentPhotoUrl));
                        }catch (Exception e1){
                            logger.error("学生=>" + studentEntity.getStudentName() + "照片没有找到！");
                            failStudentList.add(studentEntity);
                            continue;
                        }
                    }
                    params.put("cover_type", Integer.valueOf(2)); //是否需要覆盖重复人员  1--覆盖 2--不覆盖
                    logger.info("实义德添加学生开始");
                    net.sf.json.JSONObject addStudentRes;
                    addStudentRes = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_ADD_URL, addStudentParams, false, schoolThdidUrl.getAccessToken());
                    logger.info("实义德添加学生结果: " + addStudentRes.toString());
                    if (addStudentRes.getInt("code") == 0) {
                        int thdId = addStudentRes.getJSONObject("data").getInt("personnel_id");
                        ChangePersonTimeThread changePersonTimeThread = new ChangePersonTimeThread(deviceIds, thdId + "", 1,
                                1, "全体all", 999999, 111111111L, 99999999999L, "新增学生", 0, schoolThdidUrl.getPathUrl(), schoolThdidUrl.getAccessToken());
                        changePersonTimeThread.start();
                        studentEntity.setStudentThdid(thdId);//设置实义德的THDID
                        studentMapper.updateStudentThdid(studentEntity.getId(), thdId);
                        copyFile(studentPhotoUrl, "D:\\fileupload" + File.separator + schoolName);
                        reName("D:\\fileupload" + File.separator + schoolName + File.separator + studentName + photoFormat, className + "_" + studentName + photoFormat);
                        studentMapper.updateStudentInfo(studentEntity.getId(), StringUtils.isNoneBlank(photoFormat) ? schoolCode + File.separator + "student" + File.separator + className + "_" +studentName + photoFormat : null);
                    }
                }
            }
        }
        return failStudentList;

    }

    @Override
    public boolean groupInformationIntegrate() {
        Integer schoolCode = 510182006;
        List<JSONObject> listGroup = utilsMapper.listGroup(schoolCode);
        for (JSONObject group : listGroup) {
            Integer groupId = group.getInteger("id");
            String userIdString = group.getString("staff_list");
            if (StringUtils.isNoneBlank(userIdString)){
                List<String> userNameList = utilsMapper.listUserName(userIdString);
                StringBuilder userNameString = new StringBuilder();
                if (userNameList.size() > 0){
                    for (String userName : userNameList) {
                        userNameString.append(",").append(userName);
                    }
                    String groupUserName = userNameString.substring(1);
                    int size = userNameList.size();
                    utilsMapper.updateGroup(groupUserName, size, groupId);
                }
            }
        }
        return false;
    }

    @Override
    public List<UserEntity> listSchoolTeacher(Integer schoolCode, Integer gradeId, Integer classId, String[] teacherIds, String teacherName) {
        return utilsMapper.listSchoolTeacher(schoolCode, gradeId, classId, teacherIds, teacherName);
    }

    @Override
    public boolean insertVisitorPassRecord(List<VisitorPassRecord> records) {
        return utilsMapper.insertVisitorPassRecord(records) > 0;
    }

    @Override
    public List<JSONObject> listSanYuanExam() {
        return utilsMapper.listSanYuanExam();
    }

    @Override
    public List<JSONObject> listScore(String tableName) {
        return utilsMapper.listScore(tableName);
    }

    public void copyFile(String oldFilePath, String newPath) {//复制文件
        File oldFile = new File(oldFilePath);
        File newFile = new File(newPath + File.separator + oldFile.getName());//创建新抽象文件
        if(!oldFile.exists() || !oldFile.isFile()) {
            System.out.println("复制文件莫得¿¿¿");
            return;
        }
        if(newFile.exists()) {//新文件路径下有同名文件
            System.out.println("是否覆盖原有文件¿（y不覆盖|n覆盖）");
            Scanner scanner = new Scanner(System.in);
            String string = scanner.nextLine();
            if(string == "n") {
                newFile.delete();
                try {
                    newFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            else {
                newFile = new File(newPath + File.separator + "(1)" + newFile.getName());
                try {
                    newFile.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        else {
            try {
                newFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            FileInputStream fin = new FileInputStream(oldFile);//输入流
            try {
                FileOutputStream fout = new FileOutputStream(newFile,true);//输出流
                byte[]b=new byte[1024];
                try {
                    while((fin.read(b))!=-1) {//读取到末尾 返回-1 否则返回读取的字节个数
                        fout.write(b);
                    }
                    fin.close();
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public boolean reName(String path, String newName) {//文件重命名
        //Scanner scanner=new Scanner(System.in);
        File file = new File(path);
        if(file.exists()) {
            File newfile = new File(file.getParent() + File.separator + newName);//创建新名字的抽象文件
            if(file.renameTo(newfile)) {
                System.out.println("重命名成功！");
                return true;
            }
            else {
                System.out.println("重命名失败！新文件名已存在");
                return false;
            }
        }
        else {
            System.out.println("重命名文件不存在！");
            return false;
        }

    }

}
